package com.dmw.demo.service.impl;

import com.dmw.demo.dto.QueryResult;
import com.dmw.demo.dto.Response;
import com.dmw.demo.entity.Doc;
import com.dmw.demo.service.SearcherService;
import com.dmw.demo.utils.CacheClient;
import com.dmw.demo.utils.DocSearcher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SearcherServiceImpl implements SearcherService {

    @Resource
    private CacheClient cacheClient;

    private final DocSearcher docSearcher = new DocSearcher();

    @Override
    public String search(String query, long pageNo, long pageSize) {
        // 判断 redis 中是否存在该结果的缓存
        Long size = cacheClient.size("search:" + query);
        List<Doc> docs;
        QueryResult queryResult = new QueryResult();
        // 如果缓存中存在
        if(size != 0){
            // 如果当前查询的页数是存在的
            if((pageNo-1) * pageSize >= size){
                return Response.fail("分页参数错误！");
            }
            // 返回在缓存中查询到的结果
            docs = (List<Doc>) cacheClient.getRange("search:" + query, (pageNo - 1) * pageSize, ((pageNo - 1) * pageSize + pageSize - 1));
            queryResult.setDoc(docs);
            queryResult.setLength(size);
            return Response.ok(queryResult);
        }
        // 不存在，则进行搜索
        docs = docSearcher.search(query);
        int resultSize = docs.size();
        // 搜索的结果为空，则返回空
        if (resultSize == 0) {
            return Response.Empty();
        }
        // 判断当前分页参数是否超标
        if((int) ((pageNo-1) * pageSize) >= resultSize){
            return Response.fail("分页参数错误！");
        }
        // 搜索的结果不为空，先将搜到的结果保存到 Redis 中
        cacheClient.setAll("search:" + query, docs, 1L, TimeUnit.DAYS);
        // 返回分页查询的结果
        List<Doc> docList = docs.subList((int) ((pageNo - 1) * pageSize), (int) ((pageNo - 1) * pageSize + pageSize));
        queryResult.setDoc(docList);
        queryResult.setLength(resultSize);
        return Response.ok(queryResult);
    }
}
